package com.ysc.plugin.utility.network

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.TrafficStats
import android.os.Build
import com.ysc.plugin.common.NetWorkState
import com.ysc.plugin.common.abstract.Manager
import com.ysc.plugin.common.abstract.Plugin
import com.ysc.plugin.utility.photo.PhotoManger

class NetWorkManager(): Manager() {
    private var mLastRxTx:Long = TrafficStats.getTotalRxBytes()

    companion object {
        @SuppressLint("StaticFieldLeak")
        private var instance: NetWorkManager?= null
        fun getInstance(): NetWorkManager? {
            instance ?: synchronized(this) {
                instance ?: NetWorkManager().apply { instance = this }
            }
            return instance
        }
    }

    override fun getHelp(): String {
        return "command:network;\n" +
                "category:NetWorkManager;\n" +
                "operate:{\n" +
                "  getNetSpeed:获取网络下载速度,\n" +
                "}"
    }

    override fun getName(): String {
        return "NetWorkManager"
    }

    override fun getVersion(): String {
        return "1.0.0"
    }

    override fun initManagerModule() {

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        TODO("Not yet implemented")
    }

    override fun onDestroy() {

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {

    }

    fun getNetSpeed():String {
        //获得此刻系统收到的总的流量数据
        var tempSum = TrafficStats.getTotalRxBytes()
        //得到此刻和上次的流量差值（可以设置 1 秒钟获取一次）
        var rxtxLast = tempSum - mLastRxTx
        var totalSpeed: Double = rxtxLast * 1000 / 2000.0
        mLastRxTx = tempSum
        return showSpeed(totalSpeed)//设置显示当前网速
    }

    private fun showSpeed(speed:Double):String {
        var speedString:String
        if (speed >= 1048576) {
            speedString = String.format("%.2f",(speed / 1048576)) + "MB/s"
        } else {
            speedString = String.format("%.2f",(speed / 1024)) + "KB/s"
        }
        return speedString
    }

    fun getNetworkState():Int{
        val cm = super.getActivity()!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (null == cm) {
            return NetWorkState.None.ordinal
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val activeNetInfo = cm.activeNetwork
            var nc = cm.getNetworkCapabilities(activeNetInfo)
            if(nc != null){
                if(nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
                    return NetWorkState.Wifi.ordinal
                }else if(nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)){
                    return NetWorkState.CELLULAR.ordinal
                }
            }
            else
                return NetWorkState.None.ordinal
        } else {
            var networkInfo = cm.activeNetworkInfo
            if (networkInfo != null && networkInfo.isAvailable) {
                if (networkInfo.type == ConnectivityManager.TYPE_WIFI) {//WIFI
                    return NetWorkState.Wifi.ordinal
                } else if (networkInfo.type == ConnectivityManager.TYPE_MOBILE) {//移动数据
                    return NetWorkState.CELLULAR.ordinal
                }
            }else{
                return NetWorkState.None.ordinal
            }
        }
        return NetWorkState.None.ordinal
    }
}